import { useUserStore } from 'stores/useUserStore'

export const setupRouteGuard = (router) => {
  router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore()

    // 白名单路由直接通过
    if (['login', '404', '403'].includes(to.name)) {
      next()
      return
    }

    // 未登录跳转登录页
    if (!userStore.token) {
      next({ name: 'login' })
      return
    }

    // 检查路由权限
    const permission = to.meta?.permission
    if (permission && !userStore.hasPermission(permission)) {
      next({ name: '403' })
      return
    }

    next()
  })
}
